# -*- coding: utf-8 -*-

import json

from django.utils.decorators import method_decorator
from django.utils.encoding import smart_unicode
from django.views.generic import TemplateView

from common.console import db as user_db
from common.utils import track_logging
from common.utils.api import token_required
from common.utils.decorator import response_wrapper, safe_wrapper
from common.utils.tz import (
    utc_to_local_str
)
from common.withdraw import admin_db as withdraw_db
from common.withdraw.model import WITHDRAW_CHANNEL_NOT_DELETED

_LOGGER = track_logging.getLogger(__name__)


class WithdrawChannelView(TemplateView):
    def get(self, req):
        query_dct = req.GET.dict()
        query_dct['deleted'] = str(WITHDRAW_CHANNEL_NOT_DELETED)
        cond = user_db.get_mchids_filter_by_user(req.user_id)
        if cond and not query_dct.get('mch_id'):
            query_dct['mch_id'] = cond
        items, total_count = withdraw_db.list_withdraw_channel(query_dct)

        resp_items = []
        for item in items:
            data = item.as_dict()
            data['created_at'] = utc_to_local_str(data['created_at'])
            data['updated_at'] = utc_to_local_str(data['updated_at'])
            resp_items.append(data)
        return {'list': resp_items, 'page': query_dct.get('$page', 1),
                'size': len(resp_items), 'total_count': total_count}

    @method_decorator(safe_wrapper)
    def post(self, req):
        param_dct = json.loads(req.body)
        channel = withdraw_db.create_withdraw_channel(param_dct)
        return {}

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(WithdrawChannelView, self).dispatch(*args, **kwargs)


class SingleWithdrawChannelView(TemplateView):
    def get(self, req, channel_id):
        withdraw_channel = withdraw_db.get_withdraw_channel(id=int(channel_id))

        data = withdraw_channel.as_dict()
        data['created_at'] = utc_to_local_str(data['created_at'])
        data['updated_at'] = utc_to_local_str(data['updated_at'])
        return data

    @method_decorator(safe_wrapper)
    def post(self, req, channel_id):
        return self.put(req, channel_id)

    def put(self, req, channel_id):
        query_dct = json.loads(smart_unicode(req.body))
        withdraw_db.upsert_withdraw_channel(query_dct, int(channel_id))
        return {}

    def delete(self, req, channel_id):
        withdraw_db.delete_withdraw_channel(int(channel_id))
        _LOGGER.info('delete withdraw channel : %s, user: %s', channel_id, req.user_id)
        return {}

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(SingleWithdrawChannelView, self).dispatch(*args, **kwargs)
